package cn.gzjp.modules.woms.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.constant.Constants;
import cn.gzjp.common.utils.IdGen;
import cn.gzjp.modules.sys.utils.DictUtils;
import cn.gzjp.modules.sys.utils.UserUtils;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.woms.entity.Event;
import cn.gzjp.modules.woms.service.EventService;

/**
 * 工单Controller
 * @author liyp
 * @version 2018-07-07
 */
@Controller
@RequestMapping(value = "${adminPath}/woms/event")
public class EventController extends BaseController {

	@Autowired
	private EventService eventService;
	@Autowired
	private WorkerService workerService;
	
	
	/**
	 * 工单列表页面
	 */
	@RequiresPermissions("woms:event:list")
	@RequestMapping(value = {"list", ""})
	public String list(Event event, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Event> page = eventService.findPage(new Page<Event>(request, response), event); 
		model.addAttribute("page", page);
		return "modules/woms/eventList";
	}

	/**
	 * 查看，增加，编辑工单表单页面
	 */
	@RequestMapping(value = "detail")
	public String detail(Event event, Model model) {
		model.addAttribute("event", event);
		return "modules/woms/event";
	}
	/**
	 * 批量删除
	 */
	@RequiresPermissions("woms:event:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			eventService.delete(eventService.get(id));
		}
		addMessage(redirectAttributes, "删除成功");
		return redirect("/woms/event/");
	}


	/**
	 * 导出excel文件
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Event event, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Event> page = eventService.findPage(new Page<Event>(request, response, -1), event);
    		new ExportExcel("工单", Event.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工单记录失败！失败信息："+e.getMessage());
		}
		return redirect("/woms/event/?repage");
    }


	@ModelAttribute
	public Event get(@RequestParam(required=false) String id) {
		Event entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eventService.get(id);
		}
		if (entity == null){
			entity = new Event();
		}
		return entity;
	}


	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("woms:event:import")
	@RequestMapping(value = "importZip", method=RequestMethod.POST)
	public String importZip(MultipartFile zipFile, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		try {
			String mobile = UserUtils.getUser().getLoginName();
			Worker creater = workerService.get(mobile);
			if (creater == null || !Constants.WorkerRole.creater.equals(creater.getRoles())) {
				addMessage(redirectAttributes, "您不是内场运维人员角色，导入失败!!,请确保当前登录用户为内场运维人员");
				return redirect("/woms/event/");
			}

			if (zipFile == null) {
				throw new RuntimeException("请选择zip包!");
			}
			String fileName = zipFile.getOriginalFilename();
			if (StrUtil.isBlank(fileName)) {
				throw new RuntimeException("导入文档为空!");
			}
			if (!fileName.toLowerCase().endsWith("zip")) {
				throw new RuntimeException("文档格式不正确!");

			}
			// 应用目录路径
			ServletContext sc = request.getSession().getServletContext();
			String curWebAppRoot = sc.getRealPath("/userfiles");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String tempUploadName = sdf.format(new Date());
			// 保存文件的路径
			String pathname = curWebAppRoot + File.separator + "_" + tempUploadName + ".zip";
			String zipName = FilenameUtils.getBaseName(zipFile.getOriginalFilename());
			String picDir = curWebAppRoot + File.separator + "_" + tempUploadName + File.separator + zipName;
			List<File> picFileList = null;
			try {
				File outPutFile = new File(pathname);
				FileUtils.writeByteArrayToFile(outPutFile, zipFile.getBytes());
				ZipUtil.unzip(outPutFile, Charsets.toCharset("utf-8"));
				picFileList = Arrays.asList(FileUtil.ls(picDir));
			} catch (IOException e) {
				throw new RuntimeException("zip包解压失败!");
			}
			if (picFileList == null) {
				throw new RuntimeException("zip包为空!");
			}
			String acessDir = "/userfiles/" + "_" + tempUploadName + "/" + zipName + "/";

			MultipartFile multipartFile = null;
			for (File picFile : picFileList) {
				fileName = picFile.getName();
				if (fileName.endsWith("xlsx")) {//说明是excles
					String excelFilePath = picDir + File.separator + fileName;
					File execelfile = new File(excelFilePath);
					FileInputStream input = new FileInputStream(excelFilePath);
					multipartFile = new MockMultipartFile("file", execelfile.getName(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", IOUtils.toByteArray(input));
					break;//日啊，一个压缩包只能存在一个excel文件啊
				}
			}
			if (multipartFile == null) {
				addMessage(redirectAttributes, "压缩包内没有.xlsx文件，导入失败");
				return redirect("/woms/event/");
			}

			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(multipartFile, 1, 0);
			List<Event> list = ei.getDataList(Event.class);
			for (Event event : list) {
				try {
					if (StrUtil.isBlank(event.getOperationArea())) {
						failureNum++;
						failureMsg.append("所属项目未指定,");
						continue;
					}

					String projectName = DictUtils.getDictLabel(event.getOperationArea(), "operation_area", "");
					if (StrUtil.isBlank(projectName)) {
						failureNum++;
						failureMsg.append("所属项目不存在,");
						continue;
					}

    				String eventId = IdGen.uuid();
					if (StrUtil.isNotBlank(event.getFaultPic())) {//图片存在
						eventId = event.getFaultPic().substring(0,event.getFaultPic().indexOf("."));
						event.setFaultPic(acessDir+event.getFaultPic());
					}else{
						//event.setFaultPic("/static/front/cms/img/event_default.png");
					}
					event.setEventId(eventId);
					Event existsEvent = eventService.get(event.getEventId());
					if (existsEvent != null) {
						failureNum++;
						failureMsg.append("图片名称" + event.getEventId() + "已存在,");
						continue;
					}
					event.setCreaterId(UserUtils.getUser().getLoginName());
					event.setStatus(Constants.EventStatus.create);
					event.setAchieve(Constants.EventAchieveStatus.NO);
					eventService.createEvent(event);
					successNum++;
					//推送消息给分派员
					Worker worker = new Worker();//日啊，记得放在缓存里去啊，或者放在循环外面
					worker.setRoles(Constants.WorkerRole.assigner);
					worker.setProjectId(event.getOperationArea());
					List<Worker> assignerList = workerService.findList(worker);
					for (Worker assigner : assignerList) {
						sendQyWxMessage(event, Constants.AgentId.assigner, "您有新的工单需要分派", event.getDeviceName() + "设备出现故障,请尽快处理", assigner.getId());
					}
				} catch (ConstraintViolationException ex) {
					ex.printStackTrace();
					failureNum++;
				} catch (Exception ex) {
					ex.printStackTrace();
					failureNum++;
				}
			}
			if (failureNum > 0) {
				addMessage(redirectAttributes, "已成功导入 " + successNum + " 条工单记录.失败" + failureNum + " 条工单记录|" + failureMsg.toString());
			} else {
				addMessage(redirectAttributes, "已成功导入 " + successNum + " 条工单记录");
			}

		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入工单失败！失败信息：" + e.getMessage());
		}
		return redirect("/woms/event/");
	}


}